import { loginLark, loginToken } from '@/api'
import { SET_TOKEN } from '@/store/actions'

const useAuth = () => {
  const dispatch = useDispatch()
  const { runAsync: loginLarkAsync } = useRequest(loginLark, {
    manual: true,
    cacheKey: '/login/lark'
  })
  const { runAsync: loginTokenAsync } = useRequest(loginToken, {
    manual: true,
    cacheKey: '/login/token',
    onSuccess: (data) => {
      const token = data?.data ?? ''
      dispatch({ type: SET_TOKEN, token })
      localStorage.setItem('token', token)
    }
  })
  const login = async (code: string) => {
    await loginLarkAsync({ code })
    await loginTokenAsync({ code })
  }

  const logout = () => {
    dispatch({ type: SET_TOKEN, token: '' })
    localStorage.removeItem('token')
  }
  return { login, logout }
}

export default useAuth
